﻿using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PublicClass
{
    public partial class FormTotalEnts : Form
    {
        private List<ObjectId> mList = null;
        public FormTotalEnts(List<ObjectId> lst)
        {
            InitializeComponent();
            InitHead();
            mList = lst;
            InitList();
        }

        public static bool SelectEnts(List<ObjectId> lst)
        {
            if (null == lst)
                lst = new List<ObjectId>();

            lst.Clear();

            PromptSelectionOptions opt = new PromptSelectionOptions();
            opt.MessageForAdding = "请选择实体";
            PromptSelectionResult res = CadUnits.CurEdit().GetSelection(opt);
            if (res.Status == PromptStatus.OK)
            {
                SelectionSet selectSet = res.Value;

                lst.AddRange(selectSet.GetObjectIds());

                return true;
            }


            return false;
        }

        private void InitHead()
        {
            listViewEntTotal.Columns.Add("实体类名");
            listViewEntTotal.Columns.Add("实体个数");
        }

        private void InitList()
        {
            listViewEntTotal.Items.Clear();

            Dictionary<string, int> dir = new Dictionary<string, int>();
            using (Transaction ts = CadUnits.StartTransaction())
            {
                foreach (ObjectId id in mList)
                {
                    DBObject obj = ts.GetObject(id, OpenMode.ForRead);
                    if (null == obj)
                        continue;

                    string strName = obj.GetRXClass().DxfName; // obj.ToString();//

                    if (dir.ContainsKey(strName))
                        ++dir[strName];
                    else
                        dir.Add(strName, 1);
                }
            }

            this.listViewEntTotal.BeginUpdate();  //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度 
            foreach (var item in dir)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = item.Key;
                lvi.SubItems.Add(item.Value.ToString());
                this.listViewEntTotal.Items.Add(lvi);
            }
            this.listViewEntTotal.EndUpdate();  //结束数据处理，UI界面一次性绘制。
        }

        private void buttonSelect_Click(object sender, EventArgs e)
        {
            EditorUserInteraction edUser = CadUnits.CurEdit().StartUserInteraction(this.Handle);
            
            if (SelectEnts(mList))
            {
                InitList();
            }
            edUser.End();
        }
    }
}
